package com.anrongtec.zcpt.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;

import com.anrongtec.zcpt.R;
import com.anrongtec.zcpt.base.BaseActivity;
import com.anrongtec.zcpt.callback.StringDialogCallback;
import com.anrongtec.zcpt.constant.Constant;
import com.anrongtec.zcpt.constant.PreferenceKey;
import com.anrongtec.zcpt.interfaces.HttpUtil;
import com.anrongtec.zcpt.interfaces.URLConstants;
import com.anrongtec.zcpt.interfaces.module.JsonDataRestult;
import com.anrongtec.zcpt.interfaces.module.PageList;
import com.anrongtec.zcpt.manager.APPDownloadManager;
import com.anrongtec.zcpt.manager.AppDownManagerActivity;
import com.anrongtec.zcpt.manager.AppStateManager;
import com.anrongtec.zcpt.manager.AppStateManager.AppStateListener;
import com.anrongtec.zcpt.module.AppModel;
import com.anrongtec.zcpt.module.Type;
import com.anrongtec.zcpt.tab02.AppDetailActivity;
import com.anrongtec.zcpt.util.GsonUtil;
import com.anrongtec.zcpt.util.Util;
import com.art.base.util.ApkUtils;
import com.art.base.util.FileUtils;
import com.art.base.util.PreferenceUtils;
import com.art.base.util.ToastShow;
import com.google.gson.reflect.TypeToken;
import com.lzy.okhttpserver.download.DownloadInfo;
import com.lzy.okhttpserver.download.DownloadManager;
import com.lzy.okhttpserver.download.DownloadService;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter.OnItemClickListener;
import com.zhy.adapter.recyclerview.base.ViewHolder;
import com.zhy.adapter.recyclerview.wrapper.EmptyWrapper;

import java.io.File;
import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 按类型搜索页面
 * 
 * @author cxy
 *
 */
public class TypeSearchActivity extends BaseActivity {

	private RecyclerView rv_search;

	private String content;

	private int page = 1, totalPage;

	private ArrayList<AppModel> apps;

	private CommonAdapter<AppModel> adapter;
	private EmptyWrapper<AppModel> empty;

	private Type type;
	private String typeClass;
	/** 广播接收器, 接收安装卸载 */
	private AppStateManager manager;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		initData();
		super.onCreate(savedInstanceState);
		setTitleShow(true);
		setContentView(R.layout.activity_type_search);

		initViews();

		registerAppStatus();
	}

	/**
	 * 注册广播接收器
	 */
	private void registerAppStatus() {
		manager = new AppStateManager(TypeSearchActivity.this);
		manager.begin(new AppStateListener() {

			@Override
			public void onAppUninstalled(String pkgName) {
				if (adapter != null) {
					adapter.notifyDataSetChanged();
				}
			}

			@Override
			public void onAppRelpaced(String pkgName) {
				if (adapter != null) {
					adapter.notifyDataSetChanged();
				}
			}

			@Override
			public void onAppInstalled(String pkgName) {
				if (adapter != null) {
					adapter.notifyDataSetChanged();
				}
			}
		});
	}

	@Override
	protected void onDestroy() {
		if (manager != null) {
			manager.unregisterListener();
		}
		super.onDestroy();
	}

	@Override
	protected void initData() {
		type = (Type) getIntent().getSerializableExtra(Constant.DATA);
		typeClass = getIntent().getStringExtra(Constant.TYPE);
		search();
	}

	@Override
	protected void onCreateCustomToolBar(Toolbar toolbar) {
		toolbar.setTitle(type.getName());
	}

	@Override
	protected void initViews() {

		initRecyclerView();
	}

	/**
	 * 初始化recyclerView
	 */
	private void initRecyclerView() {
		rv_search = (RecyclerView) findViewById(R.id.recycler_type_search);
		rv_search.setLayoutManager(new LinearLayoutManager(this));

		apps = new ArrayList<AppModel>();

		adapter = new CommonAdapter<AppModel>(this, R.layout.item_app, apps) {
			@Override
			protected void convert(ViewHolder holder, AppModel t, int position) {
				final AppModel app = apps.get(position);
				// holder.setImageDrawable(R.id.iv_item_app_icon,
				// app.getLocalIcon());
				ImageView iv = holder.getView(R.id.iv_item_app_icon);
				ImageLoader.getInstance().displayImage(app.getIconUrl(), iv);
				holder.setText(R.id.tv_item_app_name, app.getAppName());
				holder.setText(R.id.tv_item_app_version_name, app.getRemoteVersionName());
				holder.setRating(R.id.ratingbar_item_app_score, app.getScore());

				final DownloadInfo downloadInfo = DownloadService.getDownloadManager().getDownloadInfo(app.getUrl());
				if (downloadInfo != null && downloadInfo.getState() == DownloadManager.FINISH) {
					if (ApkUtils.isInstalled(TypeSearchActivity.this, app.getAppPackName(),
							app.getRemoteVersionCode())) {
						holder.setText(R.id.btn_item_app_install, "打开");
					} else {
						if (FileUtils.isExist(downloadInfo.getTargetPath())) {
							holder.setText(R.id.btn_item_app_install, "安装");
						} else {
							holder.setText(R.id.btn_item_app_install, "下载");
						}
					}
				}

				holder.setOnClickListener(R.id.btn_item_app_install, new OnClickListener() {
					@Override
					public void onClick(View v) {
						DownloadInfo info = DownloadService.getDownloadManager().getDownloadInfo(app.getUrl());

						if (info != null && info.getState() == DownloadManager.FINISH) {
							if (ApkUtils.isInstalled(TypeSearchActivity.this, app.getAppPackName(),
									app.getRemoteVersionCode())) {
								if (!app.getAppPackName().equals(Util.getPackageName(TypeSearchActivity.this))) {
									/*ApkUtils.openAPP(TypeSearchActivity.this, app.getAppPackName());*/
									//------------------
									if (app.getActivity() == null||app.getActivity().equals("")) {//有图标的打开方式
										ApkUtils.openAPP(TypeSearchActivity.this, app.getAppPackName());
									} else {//无图标打开方式
										//ApkUtils.openDefaultApp(getActivity(),app.getAppPackName());
										ApkUtils.openAPP(TypeSearchActivity.this, app.getAppPackName(), app.getActivity());
									}
								}
							} else {
								if (FileUtils.isExist(info.getTargetPath())) {
									ApkUtils.install(TypeSearchActivity.this, new File(info.getTargetPath()));
								} else {
									APPDownloadManager.removeTask(info.getTaskKey());
									APPDownloadManager.addTask(TypeSearchActivity.this, app, info.getListener());
									startActivity(AppDownManagerActivity.class);
								}
							}
						} else {
							APPDownloadManager.addTask(TypeSearchActivity.this, app, null);
							startActivity(AppDownManagerActivity.class);
						}
					}
				});
			}
		};

		adapter.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
				intent = new Intent(TypeSearchActivity.this, AppDetailActivity.class);
				AppModel app = apps.get(position);
				intent.putExtra(Constant.DATA, app);
				startActivity(intent);
			}

			@Override
			public boolean onItemLongClick(View view, android.support.v7.widget.RecyclerView.ViewHolder holder,
					int position) {
				return false;
			}
		});

		empty = new EmptyWrapper<AppModel>(adapter);
		empty.setEmptyView(R.layout.empty_view);

		rv_search.setAdapter(empty);

	}

	/**
	 * 搜索
	 */
	private void search() {
		String json = GsonUtil.toQueryJson(content, URLConstants.SORT_DOWNLOAD, typeClass, type.getValue(), page);
		HttpUtil.post(json, new StringDialogCallback(this, "正在搜索...") {
			@Override
			public void onResponse(boolean arg0, String arg1, Request arg2, Response arg3) {

				// TODO 上报按类型查询行为
				String accountId = PreferenceUtils.getInstance(TypeSearchActivity.this)
						.getString(PreferenceKey.ACCOUNT_ID);
				// WLData.getInstance().reportEvent(accountId,
				// Events.APP_TYPE_SEARCH);

				JsonDataRestult<PageList<AppModel>> result = GsonUtil.decode(arg1,
						new TypeToken<JsonDataRestult<PageList<AppModel>>>() {
						}.getType());
				if (URLConstants.RetCode.SUCCESS.equals(result.getRetCode())) {
					apps.clear();
					apps.addAll(result.getData().getApps());
					totalPage = result.getData().getTotalPage();
					empty.notifyDataSetChanged();
				} else {
					ToastShow.shortMessage(result.getRetMsg());
				}
			}

			@Override
			public void onError(boolean isFromCache, Call call, Response response, Exception e) {
				if (response == null) {
					ToastShow.shortMessage(getString(R.string.alert_failed_connect));
				}
				super.onError(isFromCache, call, response, e);
			}
		});
	}
}
